//var api = 'http://api.qicai.wenshendaka.com/';
//var api = 'http://192.168.199.122:3003/';
var api = 'http://api.qicai.wenshendaka.com/';//'http://192.168.199.203:3003/';

var cacheControl = '0.0.X.1';
//var cacheControl = Math.random() + '';

requirejs.config({
    baseUrl: './',
    paths: {
        jquery: 'http://cdn.bootcss.com/jquery/2.2.1/jquery.min',
        router: 'http://cdn.bootcss.com/Director/1.2.8/director.min',
        pingpp: 'lib/pingpp_pay',
        icheck: 'lib/icheck.min',
        dot: 'http://cdn.bootcss.com/jQuery.dotdotdot/1.7.4/jquery.dotdotdot.min',
        template: 'lib/art-template',
        //jgestures: 'lib/jgestures.min',
        jgestures: 'http://img.meizhanggui.cc/lib/jgestures.min',
        iscroll: 'http://cdn.bootcss.com/iScroll/5.1.3/iscroll.min',
        layer: 'http://img.meizhanggui.cc/lib/layer',
        react: 'http://cdn.bootcss.com/react/0.14.7/react',

        text: 'http://cdn.bootcss.com/require-text/2.0.12/text.min',
        css: 'http://cdn.bootcss.com/require-css/0.1.8/css.min',

        wxsdk: 'http://res.wx.qq.com/open/js/jweixin-1.0.0',

        ex: 'util/ex.js?' + cacheControl,
        db: 'util/db_extend.js?' + cacheControl,
        timer: 'util/timer.js?' + cacheControl,
        page: 'util/page.js?' + cacheControl,
        wx: 'util/wx.js?' + cacheControl,
        address: 'util/address.js?' + cacheControl,

        logger: 'components/logger/logger.js?' + cacheControl,
        anime: 'components/anime/anime.js?' + cacheControl,
        payment: 'components/payment/payment.js?' + cacheControl,

        ui: 'ui-std.css?' + cacheControl,

        fakeJSON: 'util/fakeJSON.js?' + cacheControl,

        end: ''

    },
    priority: ['text', 'css'],
    shim: {
        jquery: {
            exports: "jquery"
        },
        dot: ['jquery'],
        jgestures: ['jquery'],
        layer: {
            deps: ['jquery', 'css!http://img.meizhanggui.cc/lib/skin/layer.css']
        },
        router: {
            exports: "Router"
        },
        template: {
            exports: "template"
        },
        pingpp: {
            exports: "pingpp"
        },
        icheck: {
            deps: ['css!./lib/icheck/red.css']
        }
    }
});

//Promise
function Promise(func) {

    var _Status_ = {
        Pending: 'Pending',
        Resolved: 'Resolved',
        Rejected: 'Rejected'
    };
    this.viewStatus = function () {
        return _Status_
    };
    var DoneList = [];
    var ErrorkList = [];

    var ErrorRes = null;
    var DoneRes = null;

    this.status = _Status_.Pending;
    this.done = function (callback) {
        if (typeof callback == 'function') {
            if (this.status == _Status_.Pending) {
                DoneList.push(callback);
            } else if (this.status == _Status_.Resolved) {
                callback(DoneRes);
            }
        }
        return this;
    };
    this.error = function (callback) {
        if (typeof callback == 'function') {
            if (this.status == _Status_.Pending) {
                ErrorkList.push(callback);
            } else if (this.status == _Status_.Rejected) {
                callback(ErrorRes);
            }
        }
        return this;
    };
    this.reject = function (error) {
        if (this.status == _Status_.Pending) {
            ErrorRes = error;
            this.status = _Status_.Rejected;
            for (var i = 0; i < ErrorkList.length; i++) {
                ErrorkList[i](ErrorRes);
            }
        }
    };
    this.resolve = function (done) {
        if (this.status == _Status_.Pending) {
            DoneRes = done;
            this.status = _Status_.Resolved;
            for (var i = 0; i < DoneList.length; i++) {
                DoneList[i](DoneRes);
            }
        }
    };
    this.then = function (nfunc) {
        var lastPromise = this;
        return new Promise(function (resolve, reject) {
            lastPromise.done(function () {
                new Promise(nfunc)
                    .done(function () {
                        resolve();
                    }).error(function () {
                    reject();
                })
            });
        });
    };
    if (typeof func == 'function')func.bind(this)(this.resolve.bind(this), this.reject.bind(this));
}

//全局占坑
var template, wx, Page, ex;
var page_back_and_go = function () {
    //定义在director加载完毕后
};

//加载全局模块
require(['template', 'wx', 'jquery', 'ex', 'db', 'timer', 'router', 'page', 'jgestures', 'css!ui', 'logger'], function (te, w, j, e, d, ti, r, p, jg, ui, lo) {

    ex = e;
    template = te;
    wx = w;
    Page = p;
    db.w = $(window).width();
    db.h = $(window).height();

    template.helper('encodeURIComponent', encodeURIComponent);
    template.helper('decodeURIComponent', decodeURIComponent);


    //全局模版辅助方法
    template.helper('formatDate', function (date, format) {

        date = new Date(date);

        var map = {
            "M": date.getMonth() + 1, //月份
            "d": date.getDate(), //日
            "h": date.getHours(), //小时
            "m": date.getMinutes(), //分
            "s": date.getSeconds(), //秒
            "q": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
            var v = map[t];
            if (v !== undefined) {
                if (all.length > 1) {
                    v = '0' + v;
                    v = v.substr(v.length - 2);
                }
                return v;
            }
            else if (t === 'y') {
                return (date.getFullYear() + '').substr(4 - all.length);
            }
            return all;
        });
        return format;
    });

    template.helper('formatTime', function (time, format) {

        time = +time;
        var h, m, s, S;
        S = time % 1000;
        time = Math.floor(time / 1000);
        s = time % 60;
        time = Math.floor(time / 60);
        m = time % 60;
        time = Math.floor(time / 60);
        h = time % 60;

        var map = {
            "h": h, //小时
            "m": m, //分
            "s": s, //秒
            "S": S //毫秒
        };
        format = format.replace(/([hmsS])+/g, function (all, t) {
            var v = map[t];
            if (v !== undefined) {
                if (all.length > 1) {
                    v = '0' + v;
                    v = v.substr(v.length - 2);
                }
                return v;
            }
            return all;
        });
        return format;
    });

    //回退计数器
    var BackCounter = 0;

    //不触发路由初始化的退栈并压栈方法
    page_back_and_go = function (hash) {
        BackCounter = 1;
        history.back();
        ex.async(function () {
            location.hash = hash;
        })
    };

    function init(key, method, params) {
        if (BackCounter > 0) {
            BackCounter--;
        } else {
            var flag = key.substring(key.length, key.length - 2);
            if (flag == '_r')
                require(['r_build/' + key.substring(0, key.length - 2) + '/main.js?' + cacheControl], function (page) {
                    page[method](params);
                });
            else
                require(['path/' + key + '/main.js?' + cacheControl], function (page) {
                    page[method](params);
                });
        }
    }

    router = Router({

        //商品详情
        'productDetail/:pid': function (pid) {
            init('productDetail', 'init', {id: pid});
        },
        //首页
        '/home.*': function () {
            init('home', 'init', {});
        },
        //商品分类
        'category': function () {
            init('category', 'init', {});
        },
        //商品列表 - 标准分类
        'productList/(.*)': function (query) {
            init('productList', 'init', {query: query});
        },
        //我的
        'myself': function () {
            init('myself', 'init', {});
        },
        //购物车
        'cart': function () {
            init('cart', 'init', {});
        },
        //确认订单
        'confirmOrder': function () {
            init('confirmOrder', 'init', {});
        },
        //选择优惠券
        'selectCoupon': function () {
            init('coupon', 'select', {});
        },
        //查看优惠券
        'viewCoupon': function () {
            init('coupon', 'view', {});
        },
        //选择地址
        'selectAddress': function () {
            console.log(location.hash);
            init('address', 'select', {});
        },
        //查看地址
        'viewAddress': function () {
            init('address', 'view', {});
        },
        //新增地址
        'addAddress': function () {
            init('addAddress', 'add', {});
        },
        //修改地址
        'editAddress/:aid': function (aid) {
            init('addAddress', 'edit', {id: aid});
        },
        //订单详情
        'orderDetail/:oid': function (oid) {
            init('orderDetail', 'init', {id: oid});
        },
        //订单列表
        'orderList/:status': function (status) {
            init('orderList', 'init', {status: status});
        },
        'orderList': function () {
            init('orderList', 'init', {});
        },
        //支付成功
        'paySuccess/(.*)': function (query) {
            init('info', 'success', {query: query});
        },
        //错误
        'error/(.*)': function (query) {
            init('info', 'error', {query: query});
        }
    })
        .configure({
            notfound: function () {
                $('#page').text('notfound');
            }
        });

    router.init();


    var change = '';
    if (!location.hash) {
        change = '#/home'; //不会覆盖location.search
    }

    if (!location.search) {
        if (!change)
            change = location.hash;

        change = '?1' + change;//会覆盖location.hash
    }

    if (change)
        location.replace(change);
});